<template>
  <div class="page-header-index-wide">
    <a-row :gutter="24">
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="总销售额" :total="'￥'+totalSales">
          <div>
            <trend flag="up" style="margin-right: 16px;">
              <span slot="term">周同比</span>
              12%
            </trend>
            <trend flag="down">
              <span slot="term">日同比</span>
              11%
            </trend>
          </div>
          <template slot="footer">日均销售额<span>￥  {{avgSales}}</span></template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="总订单量" :total="totalOrder">
          <div>
            <mini-area :dataSource="orderAreaData" x="日期" y="订单量"/>
          </div>
          <template slot="footer">当日订单量<span> {{ sameDayOrder}}</span></template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="支付笔数" :total="6560 | NumberFormat">
          <div>
            <mini-bar :height="40" />
          </div>
          <template slot="footer">转化率 <span>60%</span></template>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
        <chart-card :loading="loading" title="运营活动效果" total="78%">
          <div>
            <mini-progress color="rgb(19, 194, 194)" :target="80" :percentage="78" :height="8" />
          </div>
          <template slot="footer">
            <trend flag="down" style="margin-right: 16px;">
              <span slot="term">同周比</span>
              12%
            </trend>
            <trend flag="up">
              <span slot="term">日环比</span>
              80%
            </trend>
          </template>
        </chart-card>
      </a-col>
    </a-row>

    <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <a-tab-pane loading="true" tab="月份统计" key="1">
            <a-row>
              <a-col :xl="24" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="销售额按月统计" :dataSource="salesMonthData"/>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane tab="产品排行" key="2">
            <a-row>
              <a-col :xl="24" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="产品销售排行" :dataSource="productData"/>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane tab="地区统计" key="3">
            <a-row>
              <a-col :xl="24" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="地区排行榜" :dataSource="regionData"/>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>

    <a-row>
      <a-col :span="24">
        <a-card :loading="loading" :bordered="false" title="最近一周访问量统计" :style="{ marginTop: '24px' }">
          <a-row>
            <a-col :span="6">
              <head-info title="今日IP" :content="loginfo.todayIp"></head-info>
            </a-col>
            <a-col :span="2">
              <a-spin class='circle-cust'>
                <a-icon slot="indicator" type="environment" style="font-size: 24px"  />
              </a-spin>
            </a-col>
            <a-col :span="6">
              <head-info title="今日访问" :content="loginfo.todayVisitCount"></head-info>
            </a-col>
            <a-col :span="2">
              <a-spin class='circle-cust'>
                <a-icon slot="indicator" type="team" style="font-size: 24px"  />
              </a-spin>
            </a-col>
            <a-col :span="6">
              <head-info title="总访问量" :content="loginfo.totalVisitCount"></head-info>
            </a-col>
            <a-col :span="2">
              <a-spin class='circle-cust'>
                <a-icon slot="indicator" type="rise" style="font-size: 24px"  />
              </a-spin>
            </a-col>
          </a-row>
          <line-chart-multid :fields="visitFields" :dataSource="visitInfo"></line-chart-multid>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
  import ChartCard from '@/components/ChartCard'
  import ACol from "ant-design-vue/es/grid/Col"
  import ATooltip from "ant-design-vue/es/tooltip/Tooltip"
  import MiniArea from '@/components/chart/MiniArea'
  import MiniBar from '@/components/chart/MiniBar'
  import MiniProgress from '@/components/chart/MiniProgress'
  import RankList from '@/components/chart/RankList'
  import Bar from '@/components/chart/Bar'
  import LineChartMultid from '@/components/chart/LineChartMultid'
  import HeadInfo from '@/components/tools/HeadInfo.vue'
  import {getAction} from "../../api/manage";

  import Trend from '@/components/Trend'
  import { getLoginfo,getVisitInfo } from '@/api/api'
  /**
   * @description 格式化金额
   * @param number：要格式化的数字
   * @param decimals：保留几位小数 默认0位
   * @param decPoint：小数点符号 默认.
   * @param thousandsSep：千分位符号 默认为,
   */
  export const formatMoney = (number, decimals = 0, decPoint = '.', thousandsSep = ',') => {
    number = (number + '').replace(/[^0-9+-Ee.]/g, '')
    let n = !isFinite(+number) ? 0 : +number
    let prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
    let sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
    let dec = (typeof decPoint === 'undefined') ? '.' : decPoint
    let s = ''
    let toFixedFix = function (n, prec) {
      let k = Math.pow(10, prec)
      return '' + Math.ceil(n * k) / k
    }
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
    let re = /(-?\d+)(\d{3})/
    while (re.test(s[0])) {
      s[0] = s[0].replace(re, '$1' + sep + '$2')
    }
    if ((s[1] || '').length < prec) {
      s[1] = s[1] || ''
      s[1] += new Array(prec - s[1].length + 1).join('0')
    }
    return s.join(dec)
  }

  const rankList = []
  for (let i = 0; i < 7; i++) {
    rankList.push({
      name: '白鹭岛 ' + (i+1) + ' 号店',
      total: 1234.56 - i * 100
    })
  }
  const barData = []
  for (let i = 0; i < 12; i += 1) {
    barData.push({
      x: `${i + 1}月`,
      y: Math.floor(Math.random() * 1000) + 200
    })
  }
  const salesMonthData = []
  const orderAreaData = []
  const productData = []
  const regionData = []

  export default {
    name: "IndexChart",
    components: {
      ATooltip,
      ACol,
      ChartCard,
      MiniArea,
      MiniBar,
      MiniProgress,
      RankList,
      Bar,
      Trend,
      LineChartMultid,
      HeadInfo
    },
    data() {
      return {
        loading: true,
        center: null,
        //总销售额
        totalSales:0.00,
        //日均销售额
        avgSales:0.00,
        //总订单
        totalOrder:0,
        //当日订单
        sameDayOrder:0,
        rankList,
        barData,
        salesMonthData,
        orderAreaData,
        productData,
        regionData,
        loginfo:{},
        visitFields:['ip','visit'],
        visitInfo:[],
        url: {
          analysisSales:"/fywh/analysis/sales_data",
          analysisOrder:"/fywh/analysis/order_data",
          analysisSalesMonth:"/fywh/analysis/sales_month_data",
          analysisProduct:"/fywh/analysis/product_data",
          analysisRegion:"/fywh/analysis/region_data",
        },
        indicator: <a-icon type="loading" style="font-size: 24px" spin />
      }
    },
    created() {
      setTimeout(() => {
        this.loading = !this.loading
      }, 1000)
      this.initLogInfo();
      this.getSaleAnalysis();
      this.getOrderAnalysis();
      this.getSaleMonthAnalysis();
      this.getProductAnalysis();
      this.getRegionAnalysis();
    },
    methods: {
      //获取地区排行统计数据
      getRegionAnalysis(){
        let params = "";//查询条件
        getAction(this.url.analysisRegion, params).then((res) => {
          if (res.success) {
            let regionNameStr = "";
            for (let i = 0; i < res.result.regionData.length; i++) {
              if(res.result.regionData[i].regionName=='内蒙'){
                regionNameStr="内蒙古"
              }else if(res.result.regionData[i].regionName=='黑龙'){
                regionNameStr="黑龙江"
              }else{
                regionNameStr=res.result.regionData[i].regionName
              }
              regionData.push({
                x: regionNameStr,
                y: res.result.regionData[i].amount,
              })
            }
          }else{
            for (let i = 0; i < 2; i += 1) {
              regionData.push({
                x: '暂无',
                y: formatMoney(0,2)
              })
            }
          }
        })
      },
      //获取产品销售排行统计数据
      getProductAnalysis(){
        let params = "";//查询条件
        getAction(this.url.analysisProduct, params).then((res) => {
          if (res.success) {
            for (let i = 0; i < res.result.productData.length; i++) {
              productData.push({
                x: res.result.productData[i].tradeName,
                y: res.result.productData[i].amount,
              })
            }
          }else{
            for (let i = 0; i < 2; i += 1) {
              productData.push({
                x: '暂无',
                y: formatMoney(0,2)
              })
            }
          }
        })
      },
      //获取销售额按月统计数据
      getSaleMonthAnalysis(){
        let params = "";//查询条件
        getAction(this.url.analysisSalesMonth, params).then((res) => {
          if (res.success) {
            for (let i = 0; i < res.result.monthSales.length; i++) {
              salesMonthData.push({
                x: res.result.monthSales[i].date,
                y: formatMoney(res.result.monthSales[i].monthAmount,2),
              })
            }
          }else{
            for (let i = 0; i < 12; i += 1) {
              salesMonthData.push({
                x: `${i + 1}月`,
                y: formatMoney(0,2)
              })
            }
          }
        })
      },
      //获取订单统计数据
      getOrderAnalysis(){
        let params = "";//查询条件
        getAction(this.url.analysisOrder, params).then((res) => {
          if (res.success) {
            this.totalOrder = res.result.totalOrder
            this.sameDayOrder = res.result.sameDayOrder
            for (let i = 0; i < res.result.weekOrder.length; i++) {
              orderAreaData.push({
                x: res.result.weekOrder[i].date,
                y: res.result.weekOrder[i].dayOrder,
              })
            }
          }else{
            this.totalOrder = 0
            this.sameDayOrder = 0
          }
        })
      },
      //获取销售额统计数据
      getSaleAnalysis(){
        let params = "";//查询条件
        getAction(this.url.analysisSales, params).then((res) => {
          if (res.success) {
            this.totalSales = formatMoney(res.result.totalSales,2)
            this.avgSales = formatMoney(res.result.avgSales,2)
          }else{
            this.totalSales = 0.00
            this.avgSales = 0.00
          }
        })
      },
      initLogInfo () {
        getLoginfo(null).then((res)=>{
          if(res.success){
            Object.keys(res.result).forEach(key=>{
              res.result[key] =res.result[key]+""
            })
            this.loginfo = res.result;
          }
        })
        getVisitInfo().then(res=>{
          if(res.success){
             console.log("aaaaaa",res.result)
             this.visitInfo = res.result;
           }
         })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .circle-cust{
    position: relative;
    top: 28px;
    left: -100%;
  }
  .extra-wrapper {
    line-height: 55px;
    padding-right: 24px;

    .extra-item {
      display: inline-block;
      margin-right: 24px;

      a {
        margin-left: 24px;
      }
    }
  }

  /* 首页访问量统计 */
  .head-info {
    position: relative;
    text-align: left;
    padding: 0 32px 0 0;
    min-width: 125px;

    &.center {
      text-align: center;
      padding: 0 32px;
    }

    span {
      color: rgba(0, 0, 0, .45);
      display: inline-block;
      font-size: .95rem;
      line-height: 42px;
      margin-bottom: 4px;
    }
    p {
      line-height: 42px;
      margin: 0;
      a {
        font-weight: 600;
        font-size: 1rem;
      }
    }
  }
</style>